//
//  GGStringJsonExtension.swift
//  swiftDemo
//
//  Created by JIENING ZHANG on 2020/1/13.
//  Copyright © 2020 lovivid. All rights reserved.
//

import Foundation

extension String {
    func ggJsonObj() -> Any? {
        if(self.count == 0) {
            return nil;
        }
        
        let utf8Data = self.data(using: .utf8)
        if utf8Data == nil {
            return nil;
        }
        
        let jsonObj = try? JSONSerialization.jsonObject(with: utf8Data!, options: .allowFragments)
        
        return jsonObj;
    }
}

extension Dictionary {
    func ggJsonStr() -> String? {
        if JSONSerialization.isValidJSONObject(self) {
            if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) {
                let jsonStr = String(data: jsonData, encoding: .utf8)
                return jsonStr;
            }
        }
    
        return nil;
    }
}

extension Array {
    func ggJsonStr() -> String? {
        if JSONSerialization.isValidJSONObject(self) {
            if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) {
                let jsonStr = String(data: jsonData, encoding: .utf8)
                return jsonStr;
            }
        }
    
        return nil;
    }
}
